﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO.Ports;
using DevExpress.XtraCharts;
using XChip_Common;
using SerialPortHelperLib;
using System.Windows.Forms.DataVisualization.Charting;
using XChipTool.Enties;
using Newtonsoft.Json;
using System.Threading;
using System.IO;
using System.Runtime.InteropServices;
using BinAnalysisHelp;
using AdbService;

namespace XChipTool
{




    public partial class XChip_HDR_GAMMA : DevExpress.XtraEditors.XtraUserControl
    {


        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        //记录是否使用I2C设备读写
        public bool m_open = false;
        public SerialPort sPortTemp;
        private bool isRead = false;
        List<ucsDouble> list = new List<ucsDouble>();
        long[] list_64 = new long[65];
        //记录x九个点的索引
        //int tempXKey = 0;
        addressregisterManager addrDal;
        public gammahistoryManager gammaM;
        List<addressregister> hdrList = new List<addressregister>();
        bool startMove = false;
        // 使用服务定位器获取ADB服务
        private IAdbCommandService adbService = ServiceLocator.AdbCommandService;
        public XChip_HDR_GAMMA()
        {
            InitializeComponent();
        }

        private void XChip_HDR_GAMMA_Load(object sender, EventArgs e)
        {
            chart1.Legends.Clear();
            chart1.Titles.Add("右键点击可删除黑点");
            var ser = chart1.Series[0];

            ser.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline;
            ser.BorderWidth = 2;
            ser.Color = Color.Red;

            RefreshChart();

            var chartArea = chart1.ChartAreas[0];

            chartArea.AxisX.Minimum = 0;

            chartArea.AxisX.Maximum = 256;

            chartArea.AxisY.Minimum = 0d;

            chartArea.AxisY.Maximum = 256;
            

        }
        /// <summary>
        /// 鼠标点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chart1_MouseClick(object sender, MouseEventArgs e)
        {
            //表示已经最大化点数
            //if (list.Count >= 9) return;
            var ser = chart1.Series[0];
            if (e.Button == MouseButtons.Left)
            {


            }
            if (e.Button == MouseButtons.Right) //右键 弹出框
            {
                var myTestResult = chart1.HitTest(e.X, e.Y);
                if (myTestResult.ChartElementType == System.Windows.Forms.DataVisualization.Charting.ChartElementType.DataPoint)
                {
                    //this.Cursor = Cursors.Cross;
                    int i = myTestResult.PointIndex;
                    var dp = myTestResult.Series.Points[i];

                    double doubleXValue = (dp.XValue);
                    double doubleYValue = dp.YValues[0];
                    if ((doubleXValue == 255 && doubleYValue == 255) || (doubleXValue == 0 && doubleYValue == 0))  //起始点和结束点跳过
                    {
                        return;
                    }

                    //int sysIndex = list.FindIndex(c => c.xValue == (int)doubleXValue && c.yValue == (int)doubleYValue);
                    int sysIndex = list.FindIndex(c => c.xValue >= doubleXValue - 5 && c.xValue <= doubleXValue + 5 && c.yValue >= doubleYValue - 5 && c.yValue <= doubleYValue + 5);
                    if (sysIndex >= 0)
                    {
                        list.RemoveAt(sysIndex);
                    }
                    ser.Points.Clear();
                    //清空显示xy值文本框
                    GAMMA_X.Text = string.Empty;
                    GAMMA_Y.Text = string.Empty;
                    RefreshChart();
                }

            }



        }
        void GammaListRemove(int x, int y)
        {
            //var tt = list.Where(c => c.xValue > (x - 10) && c.xValue < RangeMax).ToList();
            var tt = list.Where(c => c.xValue > RangeMin && c.xValue < RangeMax).ToList();
            foreach (var item in tt)
            {
                //if (item.xValue != RangeMin)
                //{
                list.Remove(item);
                //}

            }
            if (x > RangeMin + 3 && x < RangeMax - 3)
            {
                list.Add(new ucsDouble() { xValue = x, yValue = y, Col = Color.Black });
            }



        }
        /// 1表示0-32 2表示32-64 3表示64-96 4表示96-128 5表示128-160 6表示160-192 7表示192-224 8表示224-255
        /// 10表示32 11表示64 12表示96  13表示128 14表示160 15表示192 16表示224
        /// <summary>
        /// 存储在那个范围的值 
        /// 1表示0-16 2表示16-32 3表示32-48 4表示48-64 5表示64-96 6表示96-128 7表示128-192 8表示192-255
        /// 10表示16 11表示32 12表示48  13表示64 14表示96 15表示128 16表示192
        /// </summary>
        //int RangeTemp = -1;

        int RangeMax = -1;
        int RangeMin = -1;

        /// <summary>
        /// 鼠标按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chart1_MouseDown(object sender, MouseEventArgs e)
        {
            startMove = true;
            //符合条件就添加点位
            if (e.Button == MouseButtons.Left)
            {
                //if (list.Count > 7) return;
                double _xValue = -1;
                double _yValue = -1;

                #region 注释
                //var myTestResult = chart1.HitTest(e.X, e.Y);

                //if (myTestResult.ChartElementType == System.Windows.Forms.DataVisualization.Charting.ChartElementType.DataPoint)
                //{
                //    this.Cursor = Cursors.Cross;
                //    int i = myTestResult.PointIndex;
                //    var dp = myTestResult.Series.Points[i];

                //    double doubleXValue = (dp.XValue);
                //    double doubleYValue = dp.YValues[0];


                //    if (doubleXValue == 32 || doubleXValue == 64 || doubleXValue == 96 || doubleXValue == 128 || doubleXValue == 160 || doubleXValue == 192 || doubleXValue == 224)
                //    {
                //        int sysIndex = list.FindIndex(c => c.xValue == (int)doubleXValue && c.yValue == (int)doubleYValue);
                //        if (sysIndex >= 0)
                //        {
                //            list.RemoveAt(sysIndex);
                //        }
                //        if (doubleXValue == 32)
                //        {
                //            RangeTemp = 10;
                //        }
                //        else if (doubleXValue == 64)
                //        {
                //            RangeTemp = 11;
                //        }
                //        else if (doubleXValue == 96)
                //        {
                //            RangeTemp = 12;
                //        }
                //        else if (doubleXValue == 128)
                //        {
                //            RangeTemp = 13;
                //        }
                //        else if (doubleXValue == 160)
                //        {
                //            RangeTemp = 14;
                //        }
                //        else if (doubleXValue == 192)
                //        {
                //            RangeTemp = 15;
                //        }
                //        else if (doubleXValue == 224)
                //        {
                //            RangeTemp = 16;
                //        }

                //    }


                //    //ser.Points.Clear();
                //}
                //else
                //{ 
                #endregion
                var area = chart1.ChartAreas[0];
                try
                {
                    _xValue = (int)area.AxisX.PixelPositionToValue(e.X);
                    _yValue = area.AxisY.PixelPositionToValue(e.Y);
                }
                catch (Exception)
                {
                    return;
                }

                RangeMin = list.Where(c => c.xValue < ((_xValue - 5) < 1 ? 1 : _xValue - 5)).Max(c => c.xValue);
                RangeMax = list.Where(c => c.xValue > ((_xValue + 5) > 254 ? 254 : _xValue + 5)).Min(c => c.xValue);
                //RangeMin = list.Where(c => c.xValue < _xValue).Max(c => c.xValue);
                //RangeMax = list.Where(c => c.xValue > _xValue).Min(c => c.xValue);
                int sysIndex = list.FindIndex(c => c.xValue > RangeMin && c.xValue < RangeMax);
                if (sysIndex >= 0)
                {
                    list.RemoveAt(sysIndex);
                }

                #region 折叠代码
                //    if (_xValue > 14&&_xValue<18)// _xValue == 16  _xValue > 30&&_xValue<34 _xValue == 32
                //    {
                //            int sysIndex = list.FindIndex(c => c.xValue>14 && c.xValue < 18 );
                //            if (sysIndex >= 0)
                //            {
                //                list.RemoveAt(sysIndex);
                //            }
                //            RangeTemp = 10;
                //        }
                //       else if (_xValue > 30 && _xValue < 34)//_xValue == 32  _xValue >62&&_xValue<66 _xValue == 64
                //    {
                //            int sysIndex = list.FindIndex(c => c.xValue  > 30 && c.xValue < 34);
                //            if (sysIndex >= 0)
                //            {
                //                list.RemoveAt(sysIndex);
                //            }
                //            RangeTemp = 11;
                //        }
                //        else if (_xValue >46&&_xValue<50) //_xValue == 48  _xValue >94&&_xValue<98 _xValue == 96
                //    {
                //            int sysIndex = list.FindIndex(c => c.xValue > 46 && c.xValue < 50);
                //            if (sysIndex >= 0)
                //            {
                //                list.RemoveAt(sysIndex);
                //            }
                //            RangeTemp = 12;
                //        }
                //        else if (_xValue >62&&_xValue<66)//_xValue == 64  _xValue >126&&_xValue<130 _xValue == 128
                //    {
                //            int sysIndex = list.FindIndex(c => c.xValue  > 62 && c.xValue < 66);
                //            if (sysIndex >= 0)
                //            {
                //                list.RemoveAt(sysIndex);
                //            }
                //            RangeTemp = 13;
                //        }
                //        else if (_xValue>94&&_xValue<98)//_xValue == 96  _xValue>158&&_xValue<162 _xValue == 160
                //    {
                //            int sysIndex = list.FindIndex(c => c.xValue  > 94 && c.xValue < 98);
                //            if (sysIndex >= 0)
                //            {
                //                list.RemoveAt(sysIndex);
                //            }
                //            RangeTemp = 14;
                //        }
                //        else if (_xValue >126&&_xValue<130)//_xValue == 128  _xValue >190&&_xValue<194 _xValue == 192
                //    {
                //            int sysIndex = list.FindIndex(c => c.xValue  > 126 && c.xValue < 130);
                //            if (sysIndex >= 0)
                //            {
                //                list.RemoveAt(sysIndex);
                //            }
                //            RangeTemp = 15;
                //        }
                //        else if (_xValue>190&&_xValue<194)//_xValue == 192  _xValue>222&&_xValue<226 _xValue == 224
                //    {
                //            int sysIndex = list.FindIndex(c => c.xValue  > 190 && c.xValue < 194);
                //            if (sysIndex >= 0)
                //            {
                //                list.RemoveAt(sysIndex);
                //            }
                //            RangeTemp = 16;
                //        }
                //        else if (_xValue > 0 && _xValue < 16)//_xValue > 0 && _xValue < 32
                //    {
                //            RangeTemp = 1;
                //        }
                //        else if (_xValue > 16 && _xValue < 32)//_xValue > 32 && _xValue < 64
                //    {
                //            RangeTemp = 2;
                //        }
                //        else if (_xValue > 32 && _xValue < 48)//_xValue > 64 && _xValue < 96
                //    {
                //            RangeTemp = 3;
                //        }
                //        else if (_xValue > 48 && _xValue < 64)//_xValue > 96 && _xValue < 128
                //    {
                //            RangeTemp = 4;
                //        }
                //        else if (_xValue > 64 && _xValue < 96)//_xValue > 128 && _xValue < 160
                //    {
                //            RangeTemp = 5;
                //        }
                //        else if (_xValue > 96 && _xValue < 128)//_xValue > 160 && _xValue < 192
                //    {
                //            RangeTemp = 6;
                //        }
                //        else if (_xValue > 128 && _xValue < 192)//_xValue > 192 && _xValue < 224
                //    {
                //            RangeTemp = 7;
                //        }
                //        else if (_xValue > 192 && _xValue < 255)//_xValue > 224 && _xValue < 255
                //    {
                //            RangeTemp = 8;
                //        }
                //        list.Add(new ucsDouble() { xValue = (int)_xValue, yValue = (int)_yValue });
                //} 
                #endregion

            }
            #region 废弃代码
            //这里添加确定x的点击的范围 赋值
            //var area = chart1.ChartAreas[0];
            //double _xValue = area.AxisX.PixelPositionToValue(e.X);
            //if (_xValue == 0)
            //{
            //    tempXKey = 0x0;
            //}
            //else if (0 < _xValue && _xValue <= 16)
            //{
            //    tempXKey = 0x8;
            //}
            //else if (16 < _xValue && _xValue <= 32)
            //{
            //    tempXKey = 0x8;

            //}
            //else if (32 < _xValue && _xValue <= 48)
            //{
            //    tempXKey = 0x10;

            //}
            //else if (48 < _xValue && _xValue <= 64)
            //{
            //    tempXKey = 0x18;

            //}
            //else if (64 < _xValue && _xValue <= 96)
            //{
            //    tempXKey = 0x20;

            //}
            //else if (96 < _xValue && _xValue <= 128)
            //{
            //    tempXKey = 0x28;

            //}
            //else if (128 < _xValue && _xValue <= 192)
            //{
            //    tempXKey = 0x30;

            //}
            //else if (192 < _xValue && _xValue < 255)
            //{
            //    tempXKey = 0x38;

            //}
            //else if (_xValue == 255)
            //{
            //    tempXKey = 0x40;
            //}

            #endregion


        }
        /// <summary>
        /// 鼠标抬起
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chart1_MouseUp(object sender, MouseEventArgs e)
        {
            startMove = false;
            #region 废弃代码
            ////这里添加y值 赋值
            //var area = chart1.ChartAreas[0];
            //double _yValue = area.AxisY.PixelPositionToValue(e.Y);
            //list_64[tempXKey] = (long)_yValue; 
            #endregion

        }
        /// <summary>
        /// 鼠标移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chart1_MouseMove(object sender, MouseEventArgs e)
        {
            var ser = chart1.Series[0];
            double _xValue = -1;
            double _yValue = -1;
            var area = chart1.ChartAreas[0];

            try
            {
                _xValue = area.AxisX.PixelPositionToValue(e.X);
                _yValue = area.AxisY.PixelPositionToValue(e.Y);
            }
            catch (Exception)
            {
                return;
            }
            if (_xValue < 256 && _xValue > -1 && _yValue < 256 && _yValue > -1)
                this.Cursor = Cursors.Cross;
            else this.Cursor = Cursors.Arrow;
            if (startMove)
            {
                if (e.Button == MouseButtons.Left)
                {

                    #region 折叠代码
                    //var myTestResult = chart1.HitTest(e.X, e.Y);

                    //if (myTestResult.ChartElementType == System.Windows.Forms.DataVisualization.Charting.ChartElementType.DataPoint)
                    //{
                    //    this.Cursor = Cursors.Cross;
                    //    int i = myTestResult.PointIndex;
                    //    var dp = myTestResult.Series.Points[i];

                    //    double doubleXValue = (dp.XValue);
                    //    double doubleYValue = dp.YValues[0];


                    //    //int sysIndex = list.FindIndex(c => c.xValue == (int)doubleXValue && c.yValue == (int)doubleYValue);
                    //    //if (sysIndex >= 0)
                    //    //{
                    //    //    list.RemoveAt(sysIndex);
                    //    //}
                    //    if (doubleXValue ==32||doubleXValue == 64||doubleXValue ==96||doubleXValue==128||doubleXValue==160||doubleXValue==192||doubleXValue==224)
                    //    {
                    //        int sysIndex = list.FindIndex(c => c.xValue == (int)doubleXValue && c.yValue == (int)doubleYValue);
                    //        if (sysIndex >= 0)
                    //        {
                    //            list.RemoveAt(sysIndex);
                    //        }
                    //        if (doubleXValue == 32)
                    //        {
                    //            _xValue = 32;
                    //            list.Add(new ucsDouble() { xValue = 32, yValue = (int)doubleYValue });
                    //        }
                    //        else if (doubleXValue == 64)
                    //        {
                    //            _xValue = 64;
                    //            list.Add(new ucsDouble() { xValue = 64, yValue = (int)doubleYValue });
                    //        }
                    //        else if (doubleXValue == 96)
                    //        {
                    //            _xValue = 96;
                    //            list.Add(new ucsDouble() { xValue = 96, yValue = (int)doubleYValue });
                    //        }
                    //        else if (doubleXValue == 128)
                    //        {
                    //            _xValue = 128;
                    //            list.Add(new ucsDouble() { xValue = 128, yValue = (int)doubleYValue });
                    //        }
                    //        else if (doubleXValue == 160)
                    //        {
                    //            _xValue = 160;
                    //            list.Add(new ucsDouble() { xValue = 128, yValue = (int)doubleYValue });
                    //        }
                    //        else if (doubleXValue == 192)
                    //        {
                    //            _xValue = 192;
                    //            list.Add(new ucsDouble() { xValue = 192, yValue = (int)doubleYValue });
                    //        }
                    //        else if (doubleXValue == 224)
                    //        {
                    //            _xValue = 224;
                    //            list.Add(new ucsDouble() { xValue = 224, yValue = (int)doubleYValue });
                    //        }

                    //    }

                    //    ser.Points.Clear();
                    //} 
                    #endregion


                    if (_xValue > 255)
                    {
                        _xValue = 255;
                    }
                    if (_yValue > 255)
                    {
                        _yValue = 255;
                    }
                    if (_xValue < 0)
                    {
                        _xValue = 0;
                    }
                    if (_yValue < 0)
                    {
                        _yValue = 0;
                    }
                    //if (list.Count <= 0)
                    //{

                    GammaListRemove((int)_xValue, (int)_yValue);
                    //list.Add(new ucsDouble() { xValue = (int)_xValue, yValue = (int)_yValue });
                    //}
                    //显示xy值文本框
                    GAMMA_X.Text = ((int)_xValue).ToString();
                    GAMMA_Y.Text = ((int)_yValue).ToString();
                    list = list.Distinct(new ModelComparer()).ToList();

                    RefreshChart();
                }

            }
        }
        /// <summary>
        /// 刷新界面
        /// </summary>
        void RefreshChart()
        {
            var ser = chart1.Series[0];
            ser.Points.Clear();
            //记录要删除的集合
            List<ucsDouble> listTemp = new List<ucsDouble>();
            foreach (var item in list)
            {
                if (item.xValue == 0 && item.yValue == 0)
                {
                    listTemp.Add(item);
                }
                if (item.xValue == 255 && item.yValue <= 255) //消除旁边y所有点位
                {
                    listTemp.Add(item);
                }
                //if (item.yValue == 255 )
                //{//删除x 不包含下列点位的无用点位
                //    if (item.xValue!=192||item.xValue!=128||item.xValue!=96||item.xValue!=64||item.xValue!=48||item.xValue!=32||item.xValue!=16)
                //    {
                //        listTemp.Add(item);
                //    }
                //}

            }

            ////删除记录点位
            foreach (var item in listTemp)
            {
                list.Remove(item);
            }

            listTemp = new List<ucsDouble>();
            listTemp.Add(new ucsDouble() { xValue = 0, yValue = 0, Col = Color.Red });
            listTemp.Add(new ucsDouble() { xValue = 255, yValue = 255, Col = Color.Red });

            listTemp.AddRange(list);
            list.Add(new ucsDouble() { xValue = 0, yValue = 0, Col = Color.Red });
            list.Add(new ucsDouble() { xValue = 255, yValue = 255, Col = Color.Red });
            listTemp = listTemp.OrderBy(c => c.xValue).ToList();
            //listTemp.Add(new ucsDouble() { xValue = int.Parse(GAMMA_X.Text), yValue = int.Parse(GAMMA_Y.Text) });
            list_64 = new long[65];
            int[] arrList ={0,2,4,6,8,10,12,14,16,
                        18,20,22,24,26,28,30,32,
                        34,36,38,40,42,44,46,48,
                        50,52,54,56,58,60,62,64,
                        68,72,76,80,84,88,92,96,
                        100,104,108,112,116,120,124,128,
                        136,144,152,160,168,176,184,192,
                        200,208,216,224,232,240,248,254};

            //创建64list数据 斜线直线
            //int[] YList = new int[8];
            //double[] oxs = { 16, 32, 48, 64, 96, 128, 192, 254 };
            //double[] OY = GetYListBSpline(listTemp, oxs);

            double[] spz = new double[256];
            if (list.Count == 2)
            {
                var num = list.Last().xValue - list.First().xValue;
                for (int i = 0; i < num + 1; i++)
                {
                    spz[i] = i;
                }
            }
            else
            {
                Lagrange ltemp = new Lagrange(listTemp.Select(c => c.xValue).ToArray(), listTemp.Select(c => (double)c.yValue).ToArray());
                spz = ltemp.Spline();
            }
            for (int i = 0; i < 65; i++)
            {
                if (!list.Exists(c => c.xValue == arrList[i]))
                {
                    listTemp.Add(new ucsDouble() { xValue = arrList[i], yValue = (int)Lagrange.CLIP_RANGE(spz[arrList[i]], 0, 255) });
                }
                list_64[i] = (int)Lagrange.CLIP_RANGE(spz[arrList[i]], 0, 255);
            }



            var listT = listTemp.OrderBy(c => c.xValue).ToList();

            for (int i = 0; i < listT.Count(); i++)
            {
                ser.Points.AddXY(listT[i].xValue, listT[i].yValue);
                ser.Points[i].MarkerColor = listT[i].Col;
            }
        }



        #region 去掉重复数据
        /// <summary>
        /// 去掉重复数据
        /// </summary>
        public class ModelComparer : IEqualityComparer<ucsDouble>
        {
            public bool Equals(ucsDouble x, ucsDouble y)
            {
                return x.xValue == y.xValue;
            }
            public int GetHashCode(ucsDouble obj)
            {
                return obj.xValue.GetHashCode();
            }
        }
        /// <summary>
        /// 去掉已有数据重复数据
        /// </summary>
        public class PointComparer : IEqualityComparer<System.Windows.Forms.DataVisualization.Charting.DataPoint>
        {
            public bool Equals(DataPoint x, DataPoint y)
            {
                return x.XValue == y.XValue && x.YValues[0] == y.YValues[0];
            }

            public int GetHashCode(DataPoint obj)
            {
                return obj.GetHashCode();
            }
        }

        #endregion
        #region 清理按钮
        private void simpleButton7_Click(object sender, EventArgs e)
        {
            //显示xy值文本框
            GAMMA_X.Text = string.Empty;
            GAMMA_Y.Text = string.Empty;

            chart1.Legends.Clear();
            list.Clear();
            var ser = chart1.Series[0];
            ser.Points.Clear();
            ser.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline;
            ser.BorderWidth = 2;
            ser.Color = Color.Red;
            list.Add(new ucsDouble() { xValue = 0, yValue = 0 });
            list.Add(new ucsDouble() { xValue = 255, yValue = 255 });
            //初始化list集合
            list_64 = new long[65];
            //list_64[0x0] = 0x0;
            //list_64[0x40] = 0xff;
            //foreach (var item in list)
            //{
            //    ser.Points.AddXY(item.xValue, item.yValue);
            //}
            RefreshChart();
        }
        #endregion
        #region Get获取
        /// <summary>
        /// 点击获取值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton5_Click(object sender, EventArgs e)
        {
            if (null == addrDal)
            {
                addrDal = new addressregisterManager();
            }
            if (hdrList.Count == 0)
            {
                hdrList = addrDal.GetList(c => c.Classify.Contains("HDR_Gamma"));
            }

            //simpleButton5.Hide();
            //this.simpleButton5.Click -= new System.EventHandler(this.simpleButton5_Click);
            //if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
            //    return;
            //}
            WaitBefore.Start("读取中", "正在加载中", 10);
            
            ratio_highlight.Text =(await GetRegister("ratio_highlight", hdrList)).ToString("X2");
            //ratio_lowlight.Text = GetRegister("ratio_lowlight", hdrList).ToString("X2");
            string Vals = string.Empty;
            Vals += (await ReadRegisterAsync(hdrList.Find(c => c.NameType.Contains("portion_highlight_h")).Address)).ToString("X2");
            Vals += (await ReadRegisterAsync(hdrList.Find(c => c.NameType.Contains("portion_highlight_l")).Address)).ToString("X2");
            portion_lighlight.Text = Vals;
            //portion_lowlight.Text = GetRegister("portion_lowlight", hdrList).ToString("X2");
            //给曲线图赋值
            var ser = chart1.Series[0];
            ser.Points.Clear();
            list.Clear();
            List<ucsDouble> listT = new List<ucsDouble>();
            List<long> gainList = new List<long>();
            List<long> slopeList = new List<long>();

            List<string> gainT = new List<string>();
            List<string> slopeT = new List<string>();
            List<string> gain16 = new List<string>();
            List<string> slope16 = new List<string>();

            List<int> gamma_gain_list = new List<int>();
            List<int> gamma_slope_list = new List<int>();
            for (int i = 0; i < 64; i++)
            {
                var gamStrL = $"gamma_gain{i.ToString().PadLeft(2, '0')}_l";
                var gamStrH = $"gamma_gain{i.ToString().PadLeft(2, '0')}_h";
                var sloStrL = $"slope_table{i.ToString().PadLeft(2, '0')}_l";
                var sloStrH = $"slope_table{i.ToString().PadLeft(2, '0')}_h";
                //这里不知道为什么要把高低位反过来
                var ntListL = hdrList.Find(c => c.NameType.ToLower().Contains(gamStrH.ToLower())).Address;
                var ntListH = hdrList.Find(c => c.NameType.ToLower().Contains(gamStrL.ToLower())).Address;
                var stListL = hdrList.Find(c => c.NameType.ToLower().Contains(sloStrH.ToLower())).Address;
                var stListH = hdrList.Find(c => c.NameType.ToLower().Contains(sloStrL.ToLower())).Address;
                var gainl = (await ReadRegisterAsync(ntListL)).ToString("X2");
                var gainh = (await ReadRegisterAsync(ntListH)).ToString("X2"); 
                gainT.Add($"{ntListH},{gainh}");
                gainT.Add($"{ntListL},{gainl}");
                gain16.Add($"{gainl}{gainh}");
                gamma_gain_list.Add(Convert.ToInt32($"{gainl}{gainh}", 16));
                var slopel = (await ReadRegisterAsync(stListL)).ToString("X2");
                var slopeh = (await ReadRegisterAsync(stListH)).ToString("X2");
                slopeT.Add($"{stListH},{slopeh}");
                slopeT.Add($"{stListL},{slopel}");
                if (slopel != "00")
                {
                    slope16.Add($"{OCCHelper.ConvertBinaryCode(slopel).ToString("X2")}{slopeh}");
                    var slopetemp = Convert.ToInt32($"{OCCHelper.ConvertBinaryCode(slopel).ToString("X2")}{slopeh}", 16);
                    gamma_slope_list.Add(OCCHelper.ConvertComplementCode(slopetemp));
                }
                else
                {
                    slope16.Add($"{slopel}{slopeh}");
                    gamma_slope_list.Add(Convert.ToInt32($"{slopel}{slopeh}", 16));
                }

            }
            File.WriteAllText($"{Application.StartupPath}\\TempGama\\outgain获取初始.txt", JsonConvert.SerializeObject(gainT));
            File.WriteAllText($"{Application.StartupPath}\\TempGama\\outslope获取初始.txt", JsonConvert.SerializeObject(slopeT));

            File.WriteAllText($"{Application.StartupPath}\\TempGama\\outgain组合.txt", JsonConvert.SerializeObject(gain16));
            File.WriteAllText($"{Application.StartupPath}\\TempGama\\outslope组合.txt", JsonConvert.SerializeObject(slope16));

            File.WriteAllText($"{Application.StartupPath}\\TempGama\\outgain组合32.txt", JsonConvert.SerializeObject(gamma_gain_list));
            File.WriteAllText($"{Application.StartupPath}\\TempGama\\outslope组合32.txt", JsonConvert.SerializeObject(gamma_slope_list));

            int[] gamma_x_list_restore = { 0,
        2, 4, 6, 8, 10, 12, 14, 16,
        18, 20, 22, 24, 26, 28, 30, 32,
        34, 36, 38, 40, 42, 44, 46, 48,
        50, 52, 54, 56, 58, 60, 62, 64,
        68, 72, 76, 80, 84, 88, 92, 96,
        100, 104, 108, 112, 116, 120, 124, 128,
        136, 144, 152, 160, 168, 176, 184, 192,
        200, 208, 216, 224, 232, 240, 248, 256 };
            int[] gamma_y_list_restore = new int[65];
            int[] gamma_x_list = {
        2, 4, 6, 8, 10, 12, 14, 16,
        18, 20, 22, 24, 26, 28, 30, 32,
        34, 36, 38, 40, 42, 44, 46, 48,
        50, 52, 54, 56, 58, 60, 62, 64,
        68, 72, 76, 80, 84, 88, 92, 96,
        100, 104, 108, 112, 116, 120, 124, 128,
        136, 144, 152, 160, 168, 176, 184, 192,
        200, 208, 216, 224, 232, 240, 248, 255,
        256};
            Program.gamma_restore(gamma_x_list, gamma_x_list_restore, gamma_y_list_restore, gamma_gain_list.ToArray(), gamma_slope_list.ToArray());
            for (int i = 0; i < 64; i++)
            {
                if (i == 0 || i == 0x8 || i == 0x10 || i == 0x18 || i == 0x20 || i == 0x28 || i == 0x30 || i == 0x38 || i == 0x3F)
                {

                    AddHdrGammaPoint(i, gamma_y_list_restore[i]);
                }
            }

            ser.Points.Clear();
            for (int i = 0; i < list.Count; i++)
            {
                ser.Points.AddXY(list[i].xValue, list[i].yValue);
                ser.Points[i].MarkerColor = list[i].Col;
            }



            RefreshChart();
            //simpleButton6_Click(null, null);
            Statusvalue();
            isRead = false;
            WaitBefore.Close();
            //simpleButton5.Show();
            //this.simpleButton5.Click += new System.EventHandler(this.simpleButton5_Click);
        }



        #region ADB异步读写


        /// <summary>
        /// 异步读取单个寄存器并更新文本框
        /// </summary>
        private async Task ReadRegisterAndUpdateTextAsync(string address, TextEdit textEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");

                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                await adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    string processedValue = record.Values;
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    Console.WriteLine($"[ADBForm] 成功读取寄存器 {address} 值: {processedValue}");

                    // 处理位操作
                    string displayValue;
                    if (processedValue != "0")
                    {
                        var uintValue = BitsHelp.GetBitsToUint(bits, hex, processedValue);
                        displayValue = uintValue.ToString("X");
                        Console.WriteLine($"[ADBForm] 寄存器 {address} Bits处理后值: {displayValue} (bits:{bits}, hex:{hex})");
                    }
                    else
                    {
                        displayValue = "0";
                    }

                    // 更新UI
                    UpdateTextEdit(textEdit, displayValue);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    UpdateTextEdit(textEdit, "0");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 异步读取多个寄存器并组合更新文本框
        /// </summary>
        private async Task ReadMultipleRegistersAndUpdateTextAsync(List<addressregister> nList, TextEdit textEdit)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取多个寄存器，数量: {nList.Count}");

                string combinedValue = string.Empty;

                // 按预定义的优先级顺序读取寄存器
                var priorityOrder = new[] { "_h", "_m0", "_m1", "_m2", "_m3", "_l" };

                foreach (var priority in priorityOrder)
                {
                    addressregister register = FindRegisterByPriority(nList, priority);

                    if (register != null)
                    {
                        Console.WriteLine($"[ADBForm] 读取优先级 '{priority}' 的寄存器: {register.NameType} ({register.Address})");

                        // 发送读取命令
                        string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{register.Address},0,0\"";
                        await adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{register.Address}");

                        // 等待命令执行
                        await Task.Delay(10);

                        // 获取寄存器值
                        var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(register.Address, "Read", 500));

                        if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                        {
                            string processedValue = record.Values;
                            if (processedValue.StartsWith("0x"))
                            {
                                processedValue = processedValue.Substring(2);
                            }

                            combinedValue += processedValue.PadLeft(2, '0');
                            Console.WriteLine($"[ADBForm] 成功读取 {register.Address}，当前组合值: {combinedValue}");
                        }
                        else
                        {
                            combinedValue += "00";
                            Console.WriteLine($"[ADBForm] 读取 {register.Address} 失败，使用默认值00，当前组合值: {combinedValue}");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 未找到包含 '{priority}' 的寄存器");
                    }
                }

                Console.WriteLine($"[ADBForm] 最终组合值: {combinedValue}");

                // 更新UI
                UpdateTextEdit(textEdit, combinedValue);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取多个寄存器失败: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 根据优先级查找寄存器
        /// </summary>
        private addressregister FindRegisterByPriority(List<addressregister> nList, string priority)
        {
            if (priority == "_l")
            {
                // 特殊处理 _l 寄存器
                if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                {
                    // 首先查找以 "_l" 结尾的寄存器
                    var exactMatch = nList.Find(c => c.NameType.ToLower().EndsWith("_l"));
                    if (exactMatch != null)
                    {
                        Console.WriteLine($"[ADBForm] 找到以 '_l' 结尾的寄存器: {exactMatch.NameType}");
                        return exactMatch;
                    }
                    else
                    {
                        // 如果没有以 "_l" 结尾的，则使用最后一个包含 "_l" 的寄存器
                        var containsMatch = nList.Last(c => c.NameType.ToLower().Contains("_l"));
                        Console.WriteLine($"[ADBForm] 找到包含 '_l' 的寄存器: {containsMatch.NameType}");
                        return containsMatch;
                    }
                }
            }
            else
            {
                // 其他寄存器正常处理
                var register = nList.Find(c => c.NameType.ToLower().Contains(priority));
                if (register != null)
                {
                    Console.WriteLine($"[ADBForm] 找到包含 '{priority}' 的寄存器: {register.NameType}");
                    return register;
                }
            }

            return null;
        }

        /// <summary>
        /// 更新文本框的辅助方法
        /// </summary>
        private void UpdateTextEdit(TextEdit textEdit, string value)
        {
            if (textEdit.InvokeRequired)
            {
                textEdit.Invoke(new Action(() =>
                {
                    textEdit.Text = value;
                    Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
                }));
            }
            else
            {
                textEdit.Text = value;
                Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
            }
        }

        /// <summary>
        /// 异步读取寄存器并更新复选框
        /// </summary>
        private async Task ReadRegisterAndUpdateCheckAsync(string address, CheckEdit checkEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器并更新复选框: {address}");

                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                await adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                bool isChecked = false;
                if (!string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    isChecked = BitsHelp.GetBitsCheckedToBool(bits, hex, record.Values) == 0;
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值:{record.Values}, 状态:{isChecked}");
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值无效, 状态:false");
                }

                // 更新UI
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = isChecked));
                }
                else
                {
                    checkEdit.Checked = isChecked;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 更新复选框失败: {ex.Message}");
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = false));
                }
                else
                {
                    checkEdit.Checked = false;
                }
            }
        }

        /// <summary>
        /// 异步读取单个寄存器返回值
        /// </summary>
        private async Task<long> ReadRegisterAsync(string address)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");
                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                await adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    return Convert.ToInt32(record.Values, 16);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    return 0;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                return 0;
            }
        }
        /// <summary>
        /// 异步写入单个寄存器，在值不匹配时自动重试一次
        /// </summary>
        private async Task<bool> WriteRegisterAsync(string address, string value)
        {
            int maxRetries = 1; // 值不匹配时最多重试一次
            int retryCount = 0;

            while (retryCount <= maxRetries)
            {
                try
                {
                    if (retryCount > 0)
                    {
                        Console.WriteLine($"[ADBForm] 第 {retryCount} 次重试写入寄存器: {address} 值: {value}");
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 开始写入寄存器: {address} 值: {value}");
                    }

                    // 处理位操作（如果有）
                    string processedValue = value;

                    // 确保值是十六进制格式（不带0x前缀）
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    // 发送写入命令
                    string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"1,{address},{processedValue},0\"";
                    await adbService.ExecuteAdbCommandAsync(adbCommand, $"写操作 - 地址:{address} 值:{processedValue}");

                    // 等待命令执行
                    await Task.Delay(10);

                    // 验证写入是否成功 - 等待写入记录出现
                    var writeRecord = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Write", 500));

                    if (writeRecord != null && !string.IsNullOrEmpty(writeRecord.Values))
                    {
                        string actualValue = writeRecord.Values;
                        if (actualValue.StartsWith("0x"))
                        {
                            actualValue = actualValue.Substring(2);
                        }

                        // 比较写入的值是否匹配
                        bool success = string.Equals(actualValue, processedValue, StringComparison.OrdinalIgnoreCase);

                        if (success)
                        {
                            Console.WriteLine($"[ADBForm] 成功写入寄存器 {address} 值: {processedValue}");
                            return true;
                        }
                        else
                        {
                            Console.WriteLine($"[ADBForm] 写入寄存器 {address} 值不匹配，期望: {processedValue}，实际: {actualValue}");

                            // 如果不匹配且还有重试次数，则继续重试
                            if (retryCount < maxRetries)
                            {
                                retryCount++;
                                Console.WriteLine($"[ADBForm] 准备重试写入...");
                                continue; // 直接进入下一次循环，重新发送命令
                            }
                            else
                            {
                                Console.WriteLine($"[ADBForm] 写入寄存器 {address} 重试次数已用完，仍然不匹配");
                                return false;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 写入寄存器 {address} 失败，未找到写入确认记录");

                        // 如果未找到记录且还有重试次数，则重试
                        if (retryCount < maxRetries)
                        {
                            retryCount++;
                            Console.WriteLine($"[ADBForm] 准备重试写入...");
                            continue;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[ADBForm] 写入寄存器 {address} 异常: {ex.Message}");

                    // 如果异常且还有重试次数，则重试
                    if (retryCount < maxRetries)
                    {
                        retryCount++;
                        Console.WriteLine($"[ADBForm] 准备重试写入...");
                        await Task.Delay(10); // 异常后稍作延迟再重试
                        continue;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            return false; // 理论上不会执行到这里
        }




        #endregion





        private async void Statusvalue()
        {
            if ((await ReadRegisterAsync(0x20000361.ToString("X"))) == 1)
            {
                ratio_highlight.Enabled = false;
            }
            else
            {
                ratio_highlight.Enabled = true;
            }
                                
        }
        private async Task<long> GetRegister(string NType, List<addressregister> list)
        {
            long getTemp = -1;
            var ntList = list.Where(c => c.NameType.ToLower().Contains(NType.ToLower())).OrderBy(c => c.Sorting).ToList();
            switch (ntList.Count())
            {
                case 1:
                    getTemp = await ReadRegisterAsync(ntList[0].Address);
                    break;
                case 2:
                    {
                        var nHigh = await ReadRegisterAsync(ntList[1].Address);
                        var nLow = await ReadRegisterAsync(ntList[0].Address);
                        getTemp = (nHigh << 8 & 0xff00) | (nLow & 0xff);
                    }
                    break;
                case 3:
                    {
                        var nHigh = await ReadRegisterAsync(ntList[0].Address);
                        var nMiddle = await ReadRegisterAsync(ntList[1].Address);
                        var nLow = await ReadRegisterAsync(ntList[2].Address);
                        getTemp = (nHigh << 16 & 0xff0000) | ((nMiddle << 8 & 0xff00)) | (nLow & 0xff);
                    }
                    break;
                default:
                    break;
            }
            return getTemp;
        }

        private async Task SetRegister(string NType, ulong add, List<addressregister> list)
        {
            var ntList = list.Where(c => c.NameType.ToLower().Contains(NType.ToLower())).OrderBy(c => c.Sorting).ToList();

            switch (ntList.Count())
            {
                case 1:
                    await WriteRegisterAsync(ntList[0].Address, add.ToString("X"));

                    break;
                case 2:
                    {
                        //不知道为什么要反过来4.20之前是不反的7.12之后加上该判断逻辑用于反转
                        if (NType.ToLower().Contains("gamma_gain") || NType.ToLower().Contains("slope_table"))
                        {

                            await WriteRegisterAsync(ntList[1].Address, (add & 0xff).ToString("X"));
                            await WriteRegisterAsync(ntList[0].Address, ((add >> 8) & 0xff).ToString("X"));

                        }
                        else
                        {
                            await WriteRegisterAsync(ntList[0].Address, (add & 0xff).ToString("X"));
                            await WriteRegisterAsync(ntList[1].Address, ((add >> 8) & 0xff).ToString("X"));
                           
                        }

                    }
                    break;
                case 3:
                    {
                        
                        await WriteRegisterAsync(ntList[2].Address, (add & 0xff).ToString("X"));
                        await WriteRegisterAsync(ntList[1].Address, ((add >> 8) & 0xff).ToString("X"));
                        await WriteRegisterAsync(ntList[0].Address, ((add >> 16) & 0xff).ToString("X"));
                    }
                    break;
                default:
                    break;
            
            }
            
        }

        void AddHdrGammaPoint(int x, int y)
        {
            //int[] arrList ={0,2,4,6,8,10,12,14,16,
            //            18,20,22,24,26,28,30,32,
            //            34,36,38,40,42,44,46,48,
            //            50,52,54,56,58,60,62,64,
            //            68,72,76,80,84,88,92,96,
            //            100,104,108,112,116,120,124,128,
            //            136,144,152,160,168,176,184,192,
            //            200,208,216,224,232,240,248,254};
            int[] arrList ={0,
        2, 4, 6, 8, 10, 12, 14, 16,
        18, 20, 22, 24, 26, 28, 30, 32,
        34, 36, 38, 40, 42, 44, 46, 48,
        50, 52, 54, 56, 58, 60, 62, 64,
        68, 72, 76, 80, 84, 88, 92, 96,
        100, 104, 108, 112, 116, 120, 124, 128,
        136, 144, 152, 160, 168, 176, 184, 192,
        200, 208, 216, 224, 232, 240, 248, 256};
            if (arrList[x] >= 254)
            {
                list.Add(new ucsDouble() { xValue = 255, yValue = 255, Col = Color.Black });
            }
            else
            {
                list.Add(new ucsDouble() { xValue = arrList[x], yValue = y, Col = Color.Black });
            }
            list = list.Distinct(new ModelComparer()).ToList();
        }
        #endregion


        #region 方向键使用
        /// <summary>
        /// 向上
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton4_Click(object sender, EventArgs e)
        {   //使用显示出来的xy坐标
            if (string.IsNullOrEmpty(GAMMA_X.Text) || string.IsNullOrEmpty(GAMMA_Y.Text)) return;
            list.ForEach(c => {
                if (c.xValue.ToString() == GAMMA_X.Text && c.yValue.ToString() == GAMMA_Y.Text)
                {
                    c.yValue += 1;
                    if (c.yValue > 255)
                    {
                        c.yValue = 255;
                    }
                    GAMMA_Y.Text = c.yValue.ToString();
                }
            });
            RefreshChart();
        }
        /// <summary>
        /// 向左
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(GAMMA_X.Text) || string.IsNullOrEmpty(GAMMA_Y.Text)) return;
            list.ForEach(c => {
                if (c.xValue.ToString() == GAMMA_X.Text && c.yValue.ToString() == GAMMA_Y.Text)
                {
                    c.xValue -= 1;
                    if (c.xValue < 1)
                    {
                        c.xValue = 1;
                    }
                    GAMMA_X.Text = c.xValue.ToString();
                }
            });
            RefreshChart();
        }
        /// <summary>
        /// 向右
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(GAMMA_X.Text) || string.IsNullOrEmpty(GAMMA_Y.Text)) return;
            list.ForEach(c => {
                if (c.xValue.ToString() == GAMMA_X.Text && c.yValue.ToString() == GAMMA_Y.Text)
                {
                    c.xValue += 1;
                    if (c.xValue > 255)
                    {
                        c.xValue = 255;
                    }
                    GAMMA_X.Text = c.xValue.ToString();
                }
            });
            RefreshChart();
        }
        /// <summary>
        /// 向下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(GAMMA_X.Text) || string.IsNullOrEmpty(GAMMA_Y.Text)) return;
            list.ForEach(c => {
                if (c.xValue.ToString() == GAMMA_X.Text && c.yValue.ToString() == GAMMA_Y.Text)
                {
                    c.yValue -= 1;
                    if (c.yValue < 0)
                    {
                        c.yValue = 0;
                    }
                    GAMMA_Y.Text = c.yValue.ToString();
                }
            });
            RefreshChart();
        }
        #endregion
        #region 下拉框写入
        /// <summary>
        /// 写入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SHADOWHGAIN_EditValueChanged(object sender, EventArgs e)
        {

        }

        #endregion





        /// <summary>
        /// 下发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton8_Click(object sender, EventArgs e)
        {
            try
            {
                if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                    return;
                }

                //保存到数据库中
                var listTemp = new List<ucsDouble>();
                int[] arrList ={0,2,4,6,8,10,12,14,16,
                           18,20,22,24,26,28,30,32,
                           34,36,38,40,42,44,46,48,
                           50,52,54,56,58,60,62,64,
                           68,72,76,80,84,88,92,96,
                           100,104,108,112,116,120,124,128,
                           136,144,152,160,168,176,184,192,
                           200,208,216,224,232,240,248,254};
                for (int i = 0; i < 65; i++)
                {
                    listTemp.Add(new ucsDouble() { xValue = arrList[i], yValue = (int)list_64[i], Col = Color.Black });
                }
                gammahistory model = new gammahistory();
                model.CreateName = DateTime.Now.ToString("HH:mm:sss");
                model.CreationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss");
                model.HistoryTxt = JsonConvert.SerializeObject(listTemp);
                if (null == gammaM)
                {
                    gammaM = new gammahistoryManager();
                }
                gammaM.Insert(model);
                int[] gamma_x_list = {
             2, 4, 6, 8, 10, 12, 14, 16,
             18, 20, 22, 24, 26, 28, 30, 32,
             34, 36, 38, 40, 42, 44, 46, 48,
             50, 52, 54, 56, 58, 60, 62, 64,
             68, 72, 76, 80, 84, 88, 92, 96,
             100, 104, 108, 112, 116, 120, 124, 128,
             136, 144, 152, 160, 168, 176, 184, 192,
             200, 208, 216, 224, 232, 240, 248, 255,
             256};
                listTemp = new List<ucsDouble>();
                for (int i = 0; i < 65; i++)
                {
                    if (i + 1 < 65)
                    {
                        listTemp.Add(new ucsDouble() { xValue = gamma_x_list[i], yValue = (int)list_64[i + 1], Col = Color.Black });
                    }
                    else
                    {
                        listTemp.Add(new ucsDouble() { xValue = gamma_x_list[i], yValue = gamma_x_list[i], Col = Color.Black });
                    }
                }
                listTemp.ForEach(c =>
                {
                    if (c.xValue == 255)
                    {
                        c.yValue = 255;
                    }
                    if (c.xValue == 256)
                    {
                        c.yValue = 256;
                    }
                });

                //调用算法
                int[] gamma_gain_list = new int[64];
                int[] gamma_slope_list = new int[64];
                var str = Marshal.PtrToStringAnsi(Program.load_para_hdr("para_hdr.txt", gamma_x_list));
                Program.para_gamma_calc(listTemp.Select(c => c.xValue).ToArray(), listTemp.Select(c => c.yValue).ToArray(), gamma_gain_list, gamma_slope_list);  // C#调用的函数

                var inList = JsonConvert.SerializeObject(listTemp);
                var outgainList = JsonConvert.SerializeObject(gamma_gain_list);
                var outslopeList = JsonConvert.SerializeObject(gamma_slope_list);

                File.WriteAllText($"{Application.StartupPath}\\TempGama\\outXY.txt", inList);
                File.WriteAllText($"{Application.StartupPath}\\TempGama\\outgain算法原始.txt", outgainList);
                File.WriteAllText($"{Application.StartupPath}\\TempGama\\outslope算法原始.txt", outslopeList);
                //下发gamma_gain_list gamma_slope_list
                if (hdrList.Count == 0)
                {
                    if (null == addrDal)
                    {
                        addrDal = new addressregisterManager();
                    }
                    hdrList = addrDal.GetList(c => c.Classify.Contains("HDR_Gamma"));
                }
                //校验部分代码
                List<string> ugainList = new List<string>();
                for (int i = 0; i < gamma_gain_list.Count(); i++)
                {
                    if (gamma_gain_list[i] > 0 && gamma_gain_list[i] < 16384)
                    {
                        ugainList.Add((gamma_gain_list[i]).ToString("X2"));
                    }
                    else
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("gamma_gain 数值超过范围无法生成！！！");
                        return;
                    }

                }
                List<string> uslopeList = new List<string>();
                for (int i = 0; i < gamma_slope_list.Count(); i++)
                {
                    if (gamma_slope_list[i] > -8192 && gamma_slope_list[i] < 8192)
                    {
                        //uslopeList.Add($"R:{gamma_slope_list[i]}D:{OCCHelper.ConvertComplementCode(gamma_slope_list[i]).ToString("X2")}" );
                        var temp = OCCHelper.ConvertComplementCode(gamma_slope_list[i]).ToString("X2").ToUpper();
                        if (temp.Length <= 4)
                        {
                            uslopeList.Add(temp);
                        }
                        else
                        {
                            uslopeList.Add(temp.Replace("FFFF", ""));
                        }

                    }
                    else
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("gamma_slope 数值超过范围无法生成！！！");
                        return;
                    }
                }
                File.WriteAllText($"{Application.StartupPath}\\TempGama\\outugain下发.txt", JsonConvert.SerializeObject(ugainList));
                File.WriteAllText($"{Application.StartupPath}\\TempGama\\outuslope下发.txt", JsonConvert.SerializeObject(uslopeList));
                for (int i = 0; i < ugainList.Count(); i++)
                {
                    SetRegister($"gamma_gain{i.ToString().PadLeft(2, '0')}", Convert.ToUInt32(ugainList[i], 16), hdrList);
                }
                for (int i = 0; i < uslopeList.Count(); i++)
                {
                    SetRegister($"slope_table{i.ToString().PadLeft(2, '0')}", Convert.ToUInt32(uslopeList[i], 16), hdrList);
                }
                Program.gamma_validation(gamma_x_list, gamma_gain_list, gamma_slope_list, Application.StartupPath.ToArray());  // 测试函数
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"发送错误，错误信息：{ex}");
            }
        }



        private void chart1_GetToolTipText(object sender, ToolTipEventArgs e)
        {
            if (e.HitTestResult.ChartElementType == ChartElementType.DataPoint)
            {
                int i = e.HitTestResult.PointIndex;
                DataPoint dp = e.HitTestResult.Series.Points[i];
                //分别显示x轴和y轴的数值，其中{1:F3},表示显示的是float类型，精确到小数点后3位。   
                if (dp.XValue == 0 || dp.XValue == 32 || dp.XValue == 64 || dp.XValue == 96 || dp.XValue == 128 || dp.XValue == 160 || dp.XValue == 192 || dp.XValue == 224 || dp.XValue == 255)
                {
                    e.Text = string.Format("参考点位无法删除 \n X值:{0};Y值:{1} ", dp.XValue, dp.YValues[0]);
                }
                else
                {
                    e.Text = string.Format("X值:{0};Y值:{1} ", dp.XValue, dp.YValues[0]);
                }

            }
        }
        //private long GetAERegister(string nameType)
        //{
        //    if (XChipHelp.XChipAe.Where(c => c.NameType == nameType).Count() > 0)
        //        return SerialSend.ReadRegister(Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType == nameType).First().Address, 16), sPortTemp);
        //    else { DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1; }
        //}


        //private long GetGammaRegister(string nameType)
        //{
        //    if (XChipHelp.XChipGamma.Where(c => c.NameType == nameType).Count() > 0)
        //        return SerialSend.ReadRegister(Convert.ToUInt32(XChipHelp.XChipGamma.Where(c => c.NameType == nameType).First().Address, 16), sPortTemp);
        //    else { DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1; }
        //}



        private async void simpleButton9_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            //SerialSend.isDebug = false;
            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "配置文件（*.txt）|*.txt";

            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = "IQ_Setting_Gamma_" + DateTime.Now.ToString("yyyyMMddHHmms");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                StringBuilder sb = new StringBuilder();
                var Pe_dal = new parameter_exportManager();
                if (null != Pe_dal)
                {
                    WaitBefore.Start("参数导出", "正在加载中", 60);

                    //var tempList = Pe_dal.GetList(c => c.Module == "RAW Gamma"|| c.Module == "RGB Gamma");
                    //var RAWList = tempList.Where(c => c.Module == "RAW Gamma").ToList();
                    //var RGBList = tempList.Where(c => c.Module == "RGB Gamma").ToList();
                    //var tempList = Pe_dal.GetListToExport().Where(c => c.Module == "RAW Gamma" || c.Module == "RGB Gamma").OrderBy(c => c.SortNum);
                    var tempList = Pe_dal.GetListToExport().Where(c => c.Module == "HDR_Gamma").OrderBy(c => c.SortNum); 
                    var moduleList = tempList.Select(c => c.Module).Distinct();
                    #region 判断是否需要用白天的数据
                    var Pe_patch_dal = new parameter_export_patchManager();
                    var patchList = Pe_patch_dal.GetList();
                    var conditionList = tempList.Select(c => c.ConditionAddr).Distinct();
                    foreach (var item in conditionList)
                    {
                        if ((await ReadRegisterAsync(item)) == 0)
                        {
                            patchList.RemoveAll(c => c.ConditionAddr == item);
                        }
                    }
                    #endregion
                    sb.Append($"[paralist]{Environment.NewLine}");
                    sb.Append($"0xffff,0xfef1,{Environment.NewLine}");                    
                    sb.Append($"0xfffd,0x80,{Environment.NewLine}");
                    foreach (var items in moduleList)
                    {
                        sb.Append($"{Environment.NewLine}//{items}{Environment.NewLine}");
                        foreach (var item in tempList.Where(c => c.Module == items).OrderBy(c => c.SortNum))
                        {
                            try
                            {
                                sb.Append(string.IsNullOrEmpty(item.PreNote) ? "" : Environment.NewLine + item.PreNote + Environment.NewLine);
                                sb.Append(string.IsNullOrEmpty(item.addr) ? "" : item.addr);
                                if (!string.IsNullOrEmpty(item.ReadAddr))
                                {
                                    if (patchList.Count != 0 && patchList.Select(c => c.ReadAddr).Contains(item.ReadAddr))
                                    {
                                        sb.Append($",0x{(await ReadRegisterAsync(item.RelationAddr.Trim())).ToString("x2")},");
                                    }
                                    else
                                    {
                                        sb.Append($",0x{(await ReadRegisterAsync(item.ReadAddr.Trim())).ToString("x2")},");
                                    }
                                }
                                sb.Append(string.IsNullOrEmpty(item.RearNote) ? "" : item.RearNote = item.RearNote.Replace("\\n", Environment.NewLine).Replace("\\r", "\r"));
                                sb.Append(Environment.NewLine);
                            }
                            catch (Exception ex)
                            {
                                WaitBefore.Close();
                                //setShowMsg(item.RelationAddr);
                                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                                return;
                            }
                        }
                    }
                    //sb.Append("0xfffd, 0x80,\n");
                    //sb.Append($"//{RAWList.First().Module}\n");
                    //foreach (var item in RAWList)
                    //{
                    //    sb.Append(string.IsNullOrEmpty(item.PreNote) ? "" : "\n" + item.PreNote + "\n");
                    //    sb.Append(string.IsNullOrEmpty(item.addr) ? "" : item.addr);
                    //    sb.Append(string.IsNullOrEmpty(item.ReadAddr) ? "" : $",0x{SerialSend.ReadRegister((Convert.ToUInt32(item.ReadAddr, 16)), sPortTemp).ToString("x2")},");
                    //    sb.Append(string.IsNullOrEmpty(item.RearNote) ? "" : item.RearNote = item.RearNote.Replace("\\n", "\n").Replace("\\r", "\r"));
                    //    sb.Append("\n");
                    //}
                    //sb.Append($"\n//{RGBList.First().Module}\n");
                    //foreach (var item in RGBList)
                    //{
                    //    sb.Append(string.IsNullOrEmpty(item.PreNote) ? "" : "\n" + item.PreNote + "\n");
                    //    sb.Append(string.IsNullOrEmpty(item.addr) ? "" : item.addr);
                    //    sb.Append(string.IsNullOrEmpty(item.ReadAddr) ? "" : $",0x{SerialSend.ReadRegister((Convert.ToUInt32(item.ReadAddr, 16)), sPortTemp).ToString("x2")},");
                    //    sb.Append(string.IsNullOrEmpty(item.RearNote) ? "" : item.RearNote = item.RearNote.Replace("\\n", "\n").Replace("\\r", "\r"));
                    //    sb.Append("\n");
                    //}
                    System.IO.File.WriteAllText(sfd.FileName, sb.ToString());
                    WaitBefore.Close();
                    DevExpress.XtraEditors.XtraMessageBox.Show("参数导出完成");
                }
                //SerialSend.isDebug = true;
            }
        }



        private void simpleButton10_Click(object sender, EventArgs e)
        {
            //string str = "       调节 RAW 域或 RGB 域的 Gamma 曲线，Scene_Switch使能后，勾选“调试”可分别调整Day_mode、night_mode、midnight_mode场景下的Gamma曲线。\r\n       更多详见《调试工具用户手册》。";
            Thread thread = new Thread(threadPro);
            thread.Start();
        }
        private void threadPro()

        {

            MethodInvoker methodInvoker = new MethodInvoker(ShowFormB);

            BeginInvoke(methodInvoker);

        }

        private void ShowFormB()

        {
            //string str = "\t      \t 调节 RAW 域或 RGB 域的 Gamma 曲线，Scene_Switch使能后，勾选“Debug”可分别调整Day_mode、night_mode、midnight_mode场景下的Gamma曲线。\r\n"
            //   + "\t      \t 更多详见《调试工具用户手册》。";
            string str = "";
            XChip_OptimizationTips ot = new XChip_OptimizationTips("Gamma调优Tips", str);
            ot.StartPosition = FormStartPosition.CenterScreen;
            //ot.ShowDialog();
            ot.Show();

        }

        private void ratio_highlight_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                ratio_highlight_Leave(sender, null);
            }
        }

        private void ratio_lowlight_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                ratio_lowlight_Leave(sender, null);
            }
        }

        private void portion_lighlight_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                portion_lighlight_Leave(sender, null);
            }
        }

        private void portion_lowlight_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                portion_lowlight_Leave(sender, null);
            }
        }

        private void ratio_highlight_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            if (string.IsNullOrEmpty(ratio_highlight.Text)) return;
            if (hdrList.Count == 0)
            {
                if (null == addrDal)
                {
                    addrDal = new addressregisterManager();
                }
                hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            }
            SetRegister("ratio_highlight", Convert.ToUInt32(ratio_highlight.Text, 16), hdrList);
        }

        private void ratio_lowlight_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            if (string.IsNullOrEmpty(ratio_lowlight.Text)) return;
            if (hdrList.Count == 0)
            {
                if (null == addrDal)
                {
                    addrDal = new addressregisterManager();
                }
                hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            }
            SetRegister("ratio_lowlight", Convert.ToUInt32(ratio_lowlight.Text, 16), hdrList);
        }

        private async void portion_lighlight_Leave(object sender, EventArgs e)
        {
            //if (isRead) return;
            //if (string.IsNullOrEmpty(portion_lighlight.Text)) return;
            //if (hdrList.Count == 0)
            //{
            //    if (null == addrDal)
            //    {
            //        addrDal = new addressregisterManager();
            //    }
            //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            //}
            //SetRegister("portion_highlight", Convert.ToUInt32(portion_lighlight.Text, 16), hdrList);

            if (isRead) return;
             if (null != sPortTemp || !IsUsbOpen)
            {
                
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (null == addrDal)
                {
                    addrDal = new addressregisterManager();
                }
                hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
                if (hdrList.Exists(c => c.NameType.ToLower() == "portion_highlight".ToLower() + "_h"))
                {
                    var model = hdrList.Find(c => c.NameType.ToLower() == ("portion_highlight" + "_h").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                   await SetHDRRegister(model, Val);
                }
                if (hdrList.Exists(c => c.NameType.ToLower() == "portion_highlight".ToLower() + "_l"))
                {
                    var model = hdrList.Find(c => c.NameType.ToLower() == ("portion_highlight" + "_l").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    await SetHDRRegister(model, Val);
                }
            }
        }

        private void portion_lowlight_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            if (string.IsNullOrEmpty(portion_lowlight.Text)) return;
            if (hdrList.Count == 0)
            {
                if (null == addrDal)
                {
                    addrDal = new addressregisterManager();
                }
                hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            }
            SetRegister("portion_lowlight", Convert.ToUInt32(portion_lowlight.Text, 16), hdrList);
        }

        private async void simpleButton6_Click(object sender, EventArgs e)
        {
            if (hdrList.Count == 0)
            {
                if (null == addrDal)
                {
                    addrDal = new addressregisterManager();
                }
                hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            }
            ratio_highlight.Text =( await GetRegister("ratio_highlight", hdrList)).ToString("X2");
            //ratio_lowlight.Text = GetRegister("ratio_lowlight", hdrList).ToString("X2");
            string Vals = string.Empty;
            Vals += (await ReadRegisterAsync(hdrList.Find(c => c.NameType.Contains("portion_highlight_h")).Address)).ToString("X2");
            Vals += (await ReadRegisterAsync(hdrList.Find(c => c.NameType.Contains("portion_highlight_l")).Address)).ToString("X2");
            portion_lighlight.Text = Vals;
            Statusvalue();
        }

        private async Task SetHDRRegister(addressregister model, ulong add, bool isCheck = true)
        {
            if (isRead) return;

            bool success = await WriteRegisterAsync(model.Address, add.ToString("X"));

            if (!success)
            {
                Console.WriteLine($"[ADBForm] SetHDRRegister 写入失败 - 地址: {model.Address}, 值: {add:X}");
            }

        }

    }




}
